package com.cy.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.sys.dao.SysUserDao;
import com.cy.sys.dao.SysUserRoleDao;
import com.cy.sys.pojo.SysUser;
import com.cy.sys.service.SysUserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
//    使用构造函数 等同于@Autowired
//    public SysUserServiceImpl(SysUserDao sysUserDao,SysUserRoleDao sysUserRoleDao){
//        this.sysUserDao=sysUserDao;
//        this.sysUserRoleDao=sysUserRoleDao;
//    }
//
    @Override
    public List<SysUser> findUser(SysUser sysUser) {

        return sysUserDao.selectUsers(sysUser);
    }

    @Override
    public SysUser findById(Integer id) {
//        基于id查询用户以及用户对应部门信息
        SysUser sysUser = sysUserDao.selectById(id);//user,dept
        if (sysUser==null)
            throw new ServiceException("用户已不存在");
//        基于id查询用户对应的角色id
        List<Integer> roleIds = sysUserRoleDao.selectRoleIdsByUserId(id);//roles
        sysUser.setRoleIds(roleIds);
        return sysUser;
    }

    @Transactional
    @Override
    public int saveUser(SysUser sysUser) {
//        保存村用户自身信息
//        对密码进行MD5加密(MD5是一种不可逆的加密算法，只能加密不能解密，相同内容加密结果也相同)
        String password = sysUser.getPassword();
        String salt = UUID.randomUUID().toString();//盐值加密
        SimpleHash simpleHash=new SimpleHash("MD5", password, salt,1);
        password=simpleHash.toHex();//获取加密的密码
        sysUser.setPassword(password);
        sysUser.setSalt(salt);//用来与后面登录的时候进行比对
        int rows = sysUserDao.inserUser(sysUser);
//        上面保存了之后就会有id  保存用户角色关系数据
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }
    @Transactional
    @Override
    public int updateUser(SysUser sysUser) {
//        更新用户自身信息
        int rows = sysUserDao.updateUser(sysUser);
        if (rows == 0)
            throw new ServiceException("用户可能已经不存在了");
//       更新用户和角色关系数据
        sysUserRoleDao.deleteByUserId(sysUser.getId());
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    @Override
    public int validById(Integer id, Integer valid) {
        String modifiedUser = "admin";//后续是登录用户
        return sysUserDao.validById(id, valid, modifiedUser);
    }
}
